package net.myspring.middle.validator;

import net.myspring.common.utils.ValidationUtils;
import net.myspring.middle.domain.Account;
import net.myspring.middle.mapper.AccountMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

/**
 * Created by liuj on 2016-08-29.
 */
@Component
public class AccountValidator implements Validator {

    @Autowired
    private AccountMapper accountMapper;

    @Override
    public boolean supports(Class<?> clazz) {
        return Account.class.isAssignableFrom(clazz);
    }

    @Override
    public void validate(Object target, Errors errors) {
        Account account = (Account) target;
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "loginName", "error.loginName", "loginname is required.");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "roleIds", "error.roleIds", "roles is required.");
        Account checkAccount = accountMapper.findByLoginName(account.getLoginName());
        if (checkAccount != null && !checkAccount.getId().equals(account.getId())) {
            errors.rejectValue("loginName", "error.loginName", "登录名已存在");
        }
    }
}
